from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.urls import reverse
from django.core.mail import send_mail
from django.conf import settings
from django.http import HttpResponseForbidden
from .models import Tool
from .forms import ToolForm

# 自定义权限检查装饰器
def tool_permission_required(permission_name):
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            # 超级用户拥有所有权限
            if request.user.is_superuser:
                return view_func(request, *args, **kwargs)
            
            # 检查用户是否有对应权限
            user_permissions = request.user.get_user_permissions()
            if permission_name in user_permissions:
                return view_func(request, *args, **kwargs)
            else:
                messages.error(request, '您没有执行此操作的权限')
                return redirect('tools:tool_list')
        return _wrapped_view
    return decorator

@login_required
def tool_list(request):
    """工具列表"""
    tools = Tool.objects.all().order_by('-created_at')
    
    # 分页处理
    paginator = Paginator(tools, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取用户权限
    user_permissions = request.user.get_user_permissions()
    
    context = {
        'page_obj': page_obj,
        'user_permissions': user_permissions
    }
    
    return render(request, 'tools/tool_list.html', context)

@login_required
def tool_detail(request, pk):
    """工具详情"""
    tool = get_object_or_404(Tool, pk=pk)
    # 获取用户权限
    user_permissions = request.user.get_user_permissions()
    return render(request, 'tools/tool_detail.html', {'tool': tool, 'user_permissions': user_permissions})

@login_required
@tool_permission_required('tools:tool_create')
def tool_create(request):
    """创建工具"""
    if request.method == 'POST':
        form = ToolForm(request.POST)
        if form.is_valid():
            tool = form.save()
            messages.success(request, f'工具 "{tool.name}" 创建成功！')
            return redirect('tools:tool_list')
    else:
        form = ToolForm()
    
    return render(request, 'tools/tool_form.html', {'form': form, 'title': '创建工具'})

@login_required
@tool_permission_required('tools:tool_update')
def tool_update(request, pk):
    """更新工具"""
    tool = get_object_or_404(Tool, pk=pk)
    
    if request.method == 'POST':
        form = ToolForm(request.POST, instance=tool)
        if form.is_valid():
            tool = form.save()
            messages.success(request, f'工具 "{tool.name}" 更新成功！')
            return redirect('tools:tool_list')
    else:
        form = ToolForm(instance=tool)
    
    return render(request, 'tools/tool_form.html', {
        'form': form, 
        'tool': tool,
        'title': '编辑工具'
    })

@login_required
@tool_permission_required('tools:tool_delete')
def tool_delete(request, pk):
    """删除工具"""
    tool = get_object_or_404(Tool, pk=pk)
    
    if request.method == 'POST':
        tool_name = tool.name
        tool.delete()
        messages.success(request, f'工具 "{tool_name}" 删除成功！')
        return redirect('tools:tool_list')
    
    return render(request, 'tools/tool_confirm_delete.html', {'tool': tool})

# 测试邮件功能的视图
def test_email(request):
    """
    测试邮件发送功能
    """
    if request.user.is_authenticated and request.user.is_staff:
        try:
            send_mail(
                '测试邮件',
                '这是一封测试邮件，用于验证邮箱配置是否正确。',
                settings.DEFAULT_FROM_EMAIL,
                [request.user.email],  # 发送给当前用户
                fail_silently=False,
            )
            messages.success(request, '测试邮件已发送，请检查您的邮箱。')
        except Exception as e:
            messages.error(request, f'邮件发送失败: {str(e)}')
    else:
        messages.error(request, '您没有权限执行此操作。')
    
    return redirect('tools:tool_list')